package com.damagedboy.pocketbook.web.controller;

import com.damagedboy.base.exception.ReturnInfoException;
import com.damagedboy.base.po.AdminUserPO;
import com.damagedboy.pocketbook.core.po.PocketBookPO;
import com.damagedboy.pocketbook.core.service.IPocketBookSV;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/admin/pocketbook")
public class PocketBookController {
    @Autowired
    private IPocketBookSV pocketBookSV;

    @GetMapping("/search")
    public Object search(String findTime, Integer createId, HttpServletRequest request) throws ReturnInfoException {
        HttpSession session = request.getSession();
        AdminUserPO sessionuser = (AdminUserPO) session.getAttribute("adminusersession");
        Integer id = sessionuser.getId();
        if (createId == null) {
            String name = sessionuser.getName();
            if (!name.equals("admin")) {
                createId = id;
            }
        }
        if (createId == null) {
            throw new ReturnInfoException("-1", "session lose");
        }
        List<PocketBookPO> list = pocketBookSV.getList(findTime, createId);
        return list;
    }

    @GetMapping("/detail/{id}")
    public Object detail(@PathVariable("id") Integer id) {
        return pocketBookSV.getById(id);
    }

    @PostMapping("/save")
    public Object save(PocketBookPO po, HttpServletRequest request) throws ReturnInfoException {
        if (StringUtils.isEmpty(po.getParticipant())) {
            throw new ReturnInfoException("-1", "请选择参与人");
        }
        String category = po.getCategory();
        if (category.equals("晚餐")) {
            String descr = po.getDescr();
            if (StringUtils.isEmpty(descr)) {
                throw new ReturnInfoException("-1", "请填写备注");
            }
        }
        HttpSession session = request.getSession();
        AdminUserPO sessionuser = (AdminUserPO) session.getAttribute("adminusersession");
        po.setCreateId(sessionuser.getId());
        return pocketBookSV.save(po);
    }

    @RequestMapping(value = "/del/{id}", method = RequestMethod.GET)
    public Object del(@PathVariable("id") Integer id) {
        return pocketBookSV.delById(id);
    }


}
